package com.qishenyuan.competition.utils;

import com.aliyun.oss.*;
import com.qishenyuan.competition.config.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

@Slf4j
@Component
public class AliOssUtil {

    private final AliOssProperties aliOssProperties;
    private static OSS ossClient;
    private static String bucketName;

    public AliOssUtil(AliOssProperties aliOssProperties) {
        this.aliOssProperties = aliOssProperties;
    }

    /**
     * 初始化 OSS 客户端（Spring 容器启动时执行）
     */
    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret()
        );
        bucketName = aliOssProperties.getGameTeamupBucket();
        log.info("OSS Client 初始化完成，Bucket: {}", bucketName);
    }

    /**
     * 关闭 OSS 客户端（Spring 容器关闭时执行）
     */
    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
            log.info("OSS Client 已关闭");
        }
    }

    /**
     * 文件上传
     */
    public static String upload(byte[] bytes, String objectName) {
        if (ossClient == null) {
            throw new IllegalStateException("OSS Client 未初始化");
        }

        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
            log.info("文件上传成功: {}", objectName);
        } catch (OSSException | ClientException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return null;
        }

        return generatePreSignedUrl(objectName);
    }

    /**
     * 生成文件访问 URL
     */
    public static String generatePreSignedUrl(String objectName) {
        if (ossClient == null) {
            throw new IllegalStateException("OSS Client 未初始化");
        }

        try {
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000L);
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            log.info("生成预签名 URL: {}", url);
            return url.toString();
        } catch (OSSException | ClientException e) {
            log.error("生成预签名 URL 失败: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除 OSS 文件
     */
    public static void delete(String objectName) {
        if (ossClient == null) {
            throw new IllegalStateException("OSS Client 未初始化");
        }

        try {
            ossClient.deleteObject(bucketName, objectName);
            log.info("文件删除成功, objectName: {}", objectName);
        } catch (OSSException | ClientException e) {
            log.error("文件删除失败, objectName:: {}", e.getMessage(), e);
        }
    }
}
